package com.dmcb.trade.controller;

import com.dmcb.common.business.utils.HtmlUtil;
import com.dmcb.common.business.utils.WebUtil;
import com.dmcb.common.web.controller.BaseController;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.common.business.utils.WebClientUtil;
import com.dmcb.trade.business.services.ArticleCrawlerService;
import com.dmcb.trade.business.utils.*;
import com.dmcb.trade.business.entities.ArticleUrl;
import com.dmcb.trade.business.mappers.ArticleUrlMapper;
import com.gargoylesoftware.htmlunit.WebClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by miting on 2018/12/11.
 */
@Controller
public class DmbInterfaceController extends BaseController {

    Logger logger = LoggerFactory.getLogger(DmbInterfaceController.class);

    @Autowired
    private WebClientUtil webClientUtil;

    @Autowired
    private ArticleCrawlerService articleCrawlerService;
    @Autowired
    private ArticleUrlMapper articleUrlMapper;

    /**
     * 网站文章是否下架
     *
     * @param link http://k.sina.com.cn/article_6434156378_17f816f5a00100ddst.html
     * @return 返回值
     */
    @RequestMapping(value = "/trade/html")//有些链接需要在浏览器编码一下（链接中有问号的）
    @ResponseBody
    public JsonResult getArticleBody(String link) {
        System.out.println("link===" + link);
        String articleHtml;
        String domain;
        link = WebUtil.URLDecode(link);
        if (StringUtils.isBlank(link)) {
            return outputJSONError("没有输入链接");
        }
        domain = link.substring(link.indexOf("//") + 2);
        domain = domain.substring(0, domain.indexOf("/"));
        synchronized (this) {
            int tag = CrawlerUtil.tag(link);
            if (tag == -1) {
                return outputJSONError(3,"链接未解析");
            }
            if (articleUrlMapper.queryByDomain(domain) == 0) {
                addAll(link, tag, domain);
            }
            articleHtml = articleCrawlerService.parserMap.get(tag).getTitle(link);
            if (StringUtils.isBlank(articleHtml)) {
                if (link.contains("a.mp.uc.cn")) {
                    articleHtml = String.valueOf(UCTouTiaoCrawlUtil.getInfo(link));
                    if (StringUtils.isBlank(articleHtml)) {
                        addAll(link, tag, domain);
                        articleUrlMapper.updateByDomain(1, link, domain);
                        return outputJSONWarn(null, "未获取内容");
                    }
                } else if (link.contains("buluo.qq.com")) {
                    return outputJSONWarn(null, "该链接不解析");
                } else if (link.contains("news.baidu.com")) {
                    articleHtml = String.valueOf(NewsBaiDuCrawlUtil.getInfo(link));
                    if (StringUtils.isBlank(articleHtml)) {
                        addAll(link, tag, domain);
                        articleUrlMapper.updateByDomain(1, link, domain);
                        return outputJSONWarn(null, "未获取内容");
                    }
                } else if (link.contains("www.toutiao.com")) {
                    articleHtml = String.valueOf(TouTiaoCrawlUtil.getTouTiaoInfo(link));
                    if (StringUtils.isBlank(articleHtml)) {
                        addAll(link, tag, domain);
                        articleUrlMapper.updateByDomain(1, link, domain);
                        return outputJSONWarn(null, "未获取内容");
                    }
                } else if (link.contains("qq.com")) {
                    articleHtml = String.valueOf(TengXunCrawlUtil.getTengXunInfo(link));
                    if (StringUtils.isBlank(articleHtml)) {
                        addAll(link, tag, domain);
                        articleUrlMapper.updateByDomain(1, link, domain);
                        return outputJSONWarn(null, "未获取内容");
                    }
                }else if (link.contains("ifeng.com")) {
                    articleHtml = String.valueOf(FengHuangCrawlUtil.getInfo(link));
                    if (StringUtils.isBlank(articleHtml)) {
                        addAll(link, tag, domain);
                        articleUrlMapper.updateByDomain(1, link, domain);
                        return outputJSONWarn(null, "未获取内容");
                    }
                }
//                else {
//                    articleUrlMapper.updateByDomain(1, link, domain);
//                    return outputJSONError("解析异常");
//                }
            }
            if (articleHtml.contains("null") || articleHtml.contains(" 出错了！文章没有找到哦~") || articleHtml.contains("404 -")) {
                return outputJSONWarn(null, "该链接已下线");
            }
            articleUrlMapper.updateByDomain(0, link, domain);
            return outputJSONSucc(articleHtml);
        }
    }


    private String addAll(String link, int tag, String domain) {
        //获取平台名称
        String platForm = articleCrawlerService.parserMap.get(tag).getPlatForm();
        if (articleUrlMapper.queryByLink(link) == 0 && articleUrlMapper.queryByDomain(domain) == 0) {
            articleUrlMapper.insertAll(link, platForm, domain);
        }
        return domain;
    }


    @RequestMapping(value = "/article/trade")
    public String addArticle(ModelMap model) {
        List<ArticleUrl> articleUrl = articleUrlMapper.queryList();
        model.addAttribute("articleUrl", articleUrl);
        return "trade/testCrawlLink";
    }


    /**
     * 获取百家号文章字数
     *
     * @param link http://baijiahao.baidu.com/s?id=1614004321675485993
     * @return 返回值
     */

    @RequestMapping(value = "/crawl/articlenum")
    @ResponseBody

    public JsonResult getArticleNum(String link) {
        if (StringUtils.isBlank(link)) {
            return outputJSONSucc();
        }
        link = WebUtil.URLDecode(link);
        int tag = CrawlerUtil.tag(link);
        if (tag == -1) {
            return outputJSONSucc(0);
        }
        String articleHtml = articleCrawlerService.parserMap.get(tag).parseBody(link);
        articleHtml = HtmlUtil.getTextFromHtml(articleHtml);
        if (StringUtils.isBlank(articleHtml)) {
            return outputJSONSucc(0);
        }
        int num = articleHtml.length();
        return outputJSONSucc(num);
    }


}
